package algorithms.paixu;

/**
 * @功能
 * @创建时间 2020/12/20
 *交换方法类似于插入排序，大的话就按次从右往左交换，小的话就从左往右插入排序
 */
public class Quick3way {
    public static  boolean less(Comparable v,Comparable w){
        return v.compareTo(w)<0;
    }
    public static void exch(Comparable[] a,int i,int j){
        Comparable t=a[i];
        a[i]=a[j];
        a[j]=t;
    }
    private static void show(Comparable[] a){
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
    public static boolean isSorted(Comparable[] a){
        for (int i = 0; i < a.length; i++) {
            if(less(a[i],a[i-1]))
                return false;

        }
        return true;
    }
    private static int partition(Comparable[] a,int lo,int hi){
        int i = lo, j= hi+1;
        Comparable v = a[lo];
        while (true){
            while(less(a[++i],v)) if(i==hi) break;
            while(less(v,a[--i])) if(j==lo) break;
            if(i>=j) break;
            exch(a,i,j);
        }
        exch(a,lo,j);
        return j;
    }
    private static void sort(Comparable[] a,int lo, int hi){
        if(hi <= lo) return;
        int lt = lo, i = lo+1, gt =hi;
        Comparable v = a [lo];
        while (i <= gt){

            int cmp = a[i].compareTo(v);
            if     (cmp<0) exch(a,lt++,i++);
            else if(cmp>0) exch(a,i,gt--);
            else           i++;
        }
        for (int i1 = 0; i1 < a.length; i1++) {
            System.out.println(a[i1]);
        }
        sort(a,lo,lt-1);
        sort(a,gt+1,hi);
    }

    public static void main(String[] args) {
        Integer[] a={3,2,4,1,5,8,7};
        sort(a, 0,  6);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}
